package com.mediacloud.app.newsmodule.fragment.ugc.publish

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.media.MediaMetadataRetriever
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.view.inputmethod.InputMethodManager
import androidx.recyclerview.widget.LinearLayoutManager
import cc.cloudist.acplibrary.ACProgressConstant
import cc.cloudist.acplibrary.ACProgressFlower
import com.alibaba.android.arouter.launcher.ARouter
import com.baidu.location.BDLocation
import com.baidu.mapapi.search.core.PoiInfo
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.Target
import com.chinamcloud.ugc.IUGCSDKProvider
import com.jaeger.library.StatusBarUtil
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.pictureselector.GlideEngine
import com.mediacloud.app.load
import com.mediacloud.app.model.activity.SwipeBackFragmentActivity
import com.mediacloud.app.model.interfaces.ILocation
import com.mediacloud.app.model.interfaces.IPermissionsAgree
import com.mediacloud.app.model.interfaces.PermissionUtil
import com.mediacloud.app.model.interfaces.PermissionUtil.getLocation
import com.mediacloud.app.model.interfaces.PermissionUtil.isGpsEnabled
import com.mediacloud.app.model.interfaces.PermissionUtil.showGPSPop
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.fragment.baoliao.TransUtils
import com.mediacloud.app.newsmodule.fragment.baoliao.activity.BaoLiaoLocationActivity
import com.mediacloud.app.newsmodule.fragment.baoliao.activity.REQUEST_KEY
import com.mediacloud.app.newsmodule.fragment.ugc.CameraToolsKt
import com.mediacloud.app.newsmodule.fragment.ugc.MediaScanner
import com.mediacloud.app.newsmodule.fragment.ugc.mod.CmsCatalog
import com.mediacloud.app.newsmodule.fragment.ugc.mod.CmsCatalogListResult
import com.mediacloud.app.newsmodule.utils.ToastUtil
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig
import com.mediacloud.app.reslib.util.DataInvokeUtil
import com.mediacloud.app.then
import com.mediacloud.app.user.model.UserInfo
import com.mediacloud.app.user.utils.RxUtils
import com.mediacloud.app.util.ProxyUtil
import com.utils.PopKit
import kotlinx.android.synthetic.main.activity_liteav_publish.*
import okhttp3.*
import org.json.JSONObject
import org.xutils.common.util.MD5
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.*
import java.util.concurrent.TimeUnit


class LiveAvPublishActivity : SwipeBackFragmentActivity(), ICatalogListener {
    var catalogAdapter: LiteCmsCatalogListAdapter? = null
    var selectedCatalog: CmsCatalog? = null
    var logoPath: String? = null
    var mPoiInfo: PoiInfo? = null
    var videoPath: String? = null
    var videoDuration: Long = 0L
    var videoOver = false
    var imageOver = false
    var remoteVideo: String? = null
    var remoteImage: String? = null

    //是否是来自本地相机拍摄的
    var isLocalCamera: Boolean = false
    private var dialog: ACProgressFlower? = null
    override fun getLayoutResID(): Int {
        return R.layout.activity_liteav_publish
    }

    override fun getFitSystemWindow(): Boolean {
        return false
    }

    override fun getStatusBarColor(): Int {
        return Color.WHITE
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        videoPath = intent.extras?.getString("key_video_editer_path")
        intent.extras?.getBoolean("local_camera")?.let {
            isLocalCamera = it
        }
        if (!isLocalCamera) {
            logoPath = intent.extras?.getString("coverpath")
            intent.extras?.getLong("duration")?.let {
                videoDuration = it
            }
            Glide.with(this).load(logoPath).into(logo)
        } else {
            val options = RequestOptions().frame(1000000).centerCrop()
            Glide.with(this).asBitmap().load(videoPath).apply(options).listener(object : RequestListener<Bitmap> {
                override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Bitmap>?, isFirstResource: Boolean): Boolean {
                    return false
                }

                override fun onResourceReady(resource: Bitmap?, model: Any?, target: Target<Bitmap>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {

                    saveBitmap(resource)
                    return false
                }
            }).into(logo)
        }
        val lp = titleBar.layoutParams as ViewGroup.MarginLayoutParams
        lp.topMargin = (StatusBarUtil.getStatusBarHeight(this) * 1.5).toInt()
        titleBar.layoutParams = lp

        //dialog = new SimpleDialog(getActivity());
        dialog = ACProgressFlower.Builder(this)
                .direction(ACProgressConstant.DIRECT_CLOCKWISE)
                .bgColor(Color.parseColor("#ffffff"))
                .bgAlpha(1f)
                .sizeRatio(0.18f)
                .themeColor(Color.WHITE).fadeColor(Color.DKGRAY).build()
        mRecyclerView.layoutManager = LinearLayoutManager(this)
        catalogAdapter = LiteCmsCatalogListAdapter(this, this)
        mRecyclerView.adapter = catalogAdapter


        hotSelected.setOnClickListener {
            if (hotListLayout.visibility == View.VISIBLE) {
                close()
            } else {
                hintKeyBoard()
                open()
            }
        }
        back.setOnClickListener {
            PopKit.chose(this, "是否退出发布?", "退出后视频编辑内容将无法保存",
                    PopKit.ChoseItem("取消", Color.parseColor("#333333")) {

                    }, PopKit.ChoseItem("确认", Color.parseColor("#4ca9f7")) {
                finish()

            })

        }
        logoChose.setOnClickListener {
            openPhoto()
        }

        locationLayout.setOnClickListener {
            PermissionUtil.invokeLocationPermission(this, object : IPermissionsAgree {
                override fun onAgree() {
                    getLocation(this@LiveAvPublishActivity, object : ILocation {
                        override fun onLocation(location: BDLocation) {
                            val intent = Intent(this@LiveAvPublishActivity, BaoLiaoLocationActivity::class.java)
                            startActivityForResult(intent, 12358)
                        }

                        override fun onFail() {
                            if (!isGpsEnabled(this@LiveAvPublishActivity)) {
                                showGPSPop(this@LiveAvPublishActivity, "定位服务未开启", "请打开GPS定位服务")
                            }
                        }
                    })
                }

                override fun onRefuse() {}
                override fun hasPermissions() {
                    getLocation(this@LiveAvPublishActivity, object : ILocation {
                        override fun onLocation(location: BDLocation) {
                            val intent = Intent(this@LiveAvPublishActivity, BaoLiaoLocationActivity::class.java)
                            startActivityForResult(intent, 12358)
                        }

                        override fun onFail() {
                            if (!isGpsEnabled(this@LiveAvPublishActivity)) {
                                showGPSPop(this@LiveAvPublishActivity, "定位服务未开启", "请打开GPS定位服务")
                            }
                        }
                    })

                }
            })
        }

        locationCancel.setOnClickListener {
            mPoiInfo = null
            location.text = "我在哪里"
            locationIco.isSelected = mPoiInfo != null
            location.isSelected = mPoiInfo != null
            locationCancel.isSelected = mPoiInfo != null
        }
        getCmsCatalogList()
        publish.setOnClickListener {
            if (titleView.text.toString().isNullOrBlank()) {
                ToastUtil.showCustomView(this,"视频标题不能为空")
                return@setOnClickListener
            }
            if (selectedCatalog == null) {
                ToastUtil.showCustomView(this,"话题不能为空")
                return@setOnClickListener
            }
            dialog?.show()
            dialog?.setCanceledOnTouchOutside(false)
            publish.isEnabled = false
            uploadVideo(videoPath)
            uploadImage(logoPath)

        }
        saveVideo.setOnClickListener {
            PopKit.chose(this, null, "是否将此作品保存至手机？",
                    PopKit.ChoseItem("不保存", Color.parseColor("#333333")) {

                    }, PopKit.ChoseItem("保存", Color.parseColor("#333333")) {
                if (isLocalCamera) {
                    MediaScanner(this).scanFile(CameraToolsKt.file, null)
                } else {
                    ARouter.getInstance().navigation(IUGCSDKProvider::class.java)?.saveVideoToDCIM(this, videoPath, videoDuration, logoPath)
                }

            })

        }
    }

    private fun hintKeyBoard() {
        //拿到InputMethodManager
        val imm: InputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        //如果window上view获取焦点 && view不为空
        if (imm.isActive && currentFocus != null) {
            //拿到view的token 不为空
            if (currentFocus!!.windowToken != null) {
                //表示软键盘窗口总是隐藏，除非开始时以SHOW_FORCED显示。
                imm.hideSoftInputFromWindow(currentFocus!!.windowToken, 0)
            }
        }
    }

    private fun openPhoto() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                 .imageEngine(GlideEngine.createGlideEngine())
                .imageSpanCount(3)
                .enableCrop(false)
                .cropCompressQuality(70)
                .compress(true)
                .minimumCompressSize(800)
                .isGif(false)
                .previewImage(false)
                .isCamera(true)
                .selectionMode(PictureConfig.SINGLE)
                .forResult(PictureConfig.TYPE_IMAGE)
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            PopKit.chose(this, "是否退出发布?", "退出后视频编辑内容将无法保存",
                    PopKit.ChoseItem("取消", Color.parseColor("#333333")) {

                    }, PopKit.ChoseItem("确认", Color.parseColor("#4ca9f7")) {
                finish()

            })
        }
        return super.onKeyDown(keyCode, event)
    }

    private fun saveBitmap(bitmap: Bitmap?) {
        if (bitmap == null)
            return
        val sdcardDir = getExternalFilesDir(null)
        if (sdcardDir == null) {
            Log.e(TAG, "sdcardDir is null")
            return
        }
        val folder = sdcardDir.toString() + File.separator + "camera"
        val appDir = File(folder)
        if (!appDir.exists()) {
            appDir.mkdirs()
        }
        val fileName = "${System.currentTimeMillis()}.jpg"
        val saveFile = File(appDir, fileName)
        load {
            try {
                val saveImgOut = FileOutputStream(saveFile)
                bitmap.compress(Bitmap.CompressFormat.JPEG, 80, saveImgOut)
                saveImgOut.flush()
                saveImgOut.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
            saveFile
        } then {
            if (saveFile.exists()) {
                logoPath = saveFile.absolutePath
            }
        }
    }

    @SuppressLint("CheckResult")
    private fun getCmsCatalogList() {

        DataInvokeUtil.getZiMeiTiApi().getCmsCatalogList(31)
                .compose(TransUtils.fastJSonTransform(CmsCatalogListResult::class.java))
                .compose(RxUtils.schedulersTransformer())
                .subscribe {
                    if (it.data.meta.isNotEmpty()) {
                        it.data.meta[0].name = "不选择话题"
                        selectedCatalog = it.data.meta[0]
                    }
                    catalogAdapter?.setData(it.data.meta)
                }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        data?.let {
            when (requestCode) {
                PictureConfig.TYPE_IMAGE -> {
                    val mediaList = PictureSelector.obtainMultipleResult(data)
                    if (mediaList.isNotEmpty()) {
                        logoPath = mediaList[0].path
                        val option = RequestOptions().skipMemoryCache(true)
                                .diskCacheStrategy(DiskCacheStrategy.NONE)
                        Glide.with(this).load(logoPath).apply(option).into(logo)
                    }
                }
                12358 -> {
                    mPoiInfo = it.getParcelableExtra(REQUEST_KEY)
                    var address = mPoiInfo?.getName()
                    var selected = true
                    if (address.isNullOrEmpty() || "不显示位置" == address) {
                        address = "我在哪里"
                        selected = false
                    } else if ("我的地址" == address) {
                        address = mPoiInfo?.address
                    }
                    location.text = address
                    locationIco.isSelected = selected
                    location.isSelected = selected
                    locationCancel.isSelected = selected
                }
            }
        }
    }

    private fun close() {

        val animation = AnimationUtils.loadAnimation(this, R.anim.edit_nav_close)
        animation.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationStart(animation: Animation?) {
            }

            override fun onAnimationEnd(animation: Animation?) {
                hotListLayout.visibility = View.GONE
            }

            override fun onAnimationRepeat(animation: Animation?) {
            }
        })
        hotListLayout.startAnimation(animation)
    }

    private fun open() {

        val animation = AnimationUtils.loadAnimation(this, R.anim.edit_nav_show)
        animation.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationStart(animation: Animation?) {
                hotListLayout.visibility = View.VISIBLE
            }

            override fun onAnimationEnd(animation: Animation?) {

            }

            override fun onAnimationRepeat(animation: Animation?) {
            }
        })
        hotListLayout.startAnimation(animation)
    }

    @SuppressLint("SetTextI18n")
    override fun onCatalog(position: Int, catalog: CmsCatalog) {
        close()
        selectedCatalog = catalog
        if (position == 0) {
            hotSelected.setTextColor(Color.parseColor("#666666"))
            hotSelected.text = "#选择话题"
        } else {
            hotSelected.setTextColor(Color.parseColor("#7095F7"))
            hotSelected.text = "#${catalog.name}"
        }
    }

    fun publish() {
        val param: MutableMap<String, String> = HashMap()
        param["video_url"] = "$remoteVideo"
        param["title"] = titleView.text.toString()
        val user = UserInfo.getUserInfo(this)
        param["tip_image"] = "$remoteImage"
        param["user_id"] = user.userid
        param["nickname"] = user.nickname
        param["logo"] = user.avatar
        param["catalog_id"] = "${selectedCatalog?.id}"
        param["duration"] = ""
        mPoiInfo?.let {
            param["location"] = "${it.name}"
        }
        if (videoDuration != 0L) {
            param["duration"] = durationFormat(videoDuration)
        }
        if (param["duration"].isNullOrEmpty()) {

            try {
                val retriever = MediaMetadataRetriever()
                retriever.setDataSource(videoPath)
                val timeString = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)
                val time = java.lang.Long.valueOf(timeString)
                param["duration"] = durationFormat(time)
            } catch (e: Exception) {
                e.printStackTrace()
            }

        }
        load {
            val sb = StringBuffer()
            sb.append("\n")
            param.forEach {
                sb.append(it.key).append("=").append(it.value).append("\n")
            }
            Log.w("LiveAvPublish", sb.toString())
            DataInvokeUtil.ziMeiTiApi.saveShortVideo(param).execute()
        } then {
            publish.isEnabled = true
            dialog?.dismiss()
            if (it.isSuccessful) {
                val json = it.body()
                if (json!=null&&json.optBoolean("state")) {
                    ToastUtil.showCustomView(this,"发布成功")
                    finish()
                    val intent = Intent()
                    intent.putExtra("POSITION", 1)
                    intent.putExtra("SHOW_LOADING",false)
                    intent.setClassName(this, "com.mediacloud.app.appfactory.activity.smallvideo.MySmallVIdeo")
                    startActivity(intent)
                } else {
                    ToastUtil.showCustomView(this,"网络异常，请检查网络")
                }
            }
        }
    }


    private fun uploadVideo(path: String?) {
        videoOver = false
        val file = File(path)
        if (!file.exists())
            return
        load {
            upload(file)
        } then {
            if (it != null) {
                val json = JSONObject("${it.body()?.string()}")
                if (json.optInt("state") == 200 && json.optBoolean("success")) {
                    remoteVideo = json.optString("data")
                    videoOver = true
                    if (videoOver && imageOver) {
                        publish()
                    }
                } else {
                    publish.isEnabled = true
                    dialog?.dismiss()
                }

            } else {
                publish.isEnabled = true
                dialog?.dismiss()
            }
        }
    }

    private fun uploadImage(path: String?) {
        imageOver = false
        val file = File(path)
        if (!file.exists())
            return
        load {
            upload(file)
        } then {
            if (it != null) {
                val json = JSONObject("${it.body()?.string()}")
                if (json.optInt("state") == 200 && json.optBoolean("success")) {
                    remoteImage = json.optString("data")
                    imageOver = true
                    if (videoOver && imageOver) {
                        publish()
                    }
                } else {
                    publish.isEnabled = true
                    dialog?.dismiss()
                }

            } else {
                publish.isEnabled = true
                dialog?.dismiss()
            }
        }
    }

    private fun upload(file: File): Response? {
        val builder = MultipartBody.Builder()
        builder.setType(MultipartBody.FORM)
        builder.addFormDataPart(
                "file",
                MD5.md5(file.name) + "." + fileSuffix(file.absolutePath),
                RequestBody.create(MediaType.parse("application/octet-stream"), file)
        )
        builder.addFormDataPart("catalogId", "${selectedCatalog?.id}")

        val builder1 = OkHttpClient.Builder()
        builder1.readTimeout(60 * 1000 * 5, TimeUnit.MILLISECONDS)
        builder1.connectTimeout(60 * 1000 * 5, TimeUnit.MILLISECONDS)
        ProxyUtil.config(builder1)
        val httpClient = builder1.build()
        val url = AppFactoryGlobalConfig.getAppServerConfigInfo(this).spider_cms + "api/tipoff/uploadFile"
        val body = builder.build()
        try {
            val requestBuilder = Request.Builder().url(url).post(body)
            requestBuilder.addHeader("tenantId", resources.getString(R.string.tenantid))
            return httpClient.newCall(requestBuilder.build()).execute()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    private fun fileSuffix(filePath: String): String {
        val file = File(filePath)
        val fileName = file.name
        return fileName.substring(fileName.lastIndexOf(".") + 1)
    }

    private fun durationFormat(millisecond: Long): String {
        val second = millisecond / 1000
        val seconds = second % 60
        val minutes = (second / 60) % 60
        //val hours = second / 3600
//        return if (hours > 0) {
//            String.format(Locale.getDefault(), "%d:%02d:%02d", hours, minutes, seconds)
//        } else {
//            String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds)
//        }
        return String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds)
    }
}